package com.daqian.chance.qiniu.oss.service.impl;

import cn.hutool.core.util.StrUtil;
import com.daqian.chance.qiniu.oss.po.vo.OssParamsVO;
import com.daqian.chance.qiniu.oss.properties.QiniuOssProperties;
import com.daqian.chance.qiniu.oss.service.QiniuOssService;
import com.qiniu.util.Auth;
import com.qiniu.util.StringMap;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.UUID;

/**
 * @Author: daqian
 * @Date: 2019/11/26 20:17
 */
@Service
public class QiniuOssServiceImpl implements QiniuOssService {


    @Autowired
    private QiniuOssProperties qiniuOssProperties;


    @Override
    public OssParamsVO generateQiniuOssToken() {
        return this.generateQiniuOssToken(null);
    }

    @Override
    public OssParamsVO generateQiniuOssToken(String module) {
        return this.generateQiniuOssToken(module, null);
    }

    @Override
    public OssParamsVO generateQiniuOssToken(String module, String key, String keySuffix) {
        return this.generateQiniuOssToken(module, null);
    }

    @Override
    public OssParamsVO generateQiniuOssToken(String module, StringMap policy) {
        return this.generateQiniuOssToken(module, null, null, qiniuOssProperties.getExpires(), policy);
    }

    @Override
    public OssParamsVO generateQiniuOssToken(String module, String key, String keySuffix, long expires, StringMap policy) {
        return this.generateQiniuOssToken(null, module, key, keySuffix, expires, policy);
    }

    @Override
    public OssParamsVO generateQiniuOssToken(String bucket, String module, String key, String keySuffix, long expires, StringMap policy) {
        bucket = StrUtil.isEmpty(bucket) ? qiniuOssProperties.getBucket() : bucket;
        module = StrUtil.isEmpty(module) ? qiniuOssProperties.getModule() : module;
        key = StrUtil.isEmpty(key) ? UUID.randomUUID().toString().replaceAll("-", "") : key;
        keySuffix = StrUtil.isEmpty(keySuffix) ? qiniuOssProperties.getKeySuffix() : keySuffix;

        Auth auth = Auth.create(qiniuOssProperties.getAccessKey(), qiniuOssProperties.getSecretKey());
        String keyPath = String.format("%s/%s%s", module, key, keySuffix);
        String upToken = auth.uploadToken(bucket, keyPath, expires, policy);
//        String url = qiniuOssProperties.getHost() + keyPath;
        return OssParamsVO.builder()
                .host(qiniuOssProperties.getHost())
                .key(keyPath)
                .token(upToken)
                .build();
    }

}
